package org.example.Swing.handler;

import org.example.Swing.xiangmu.login.LoginView;
import org.example.Swing.xiangmu.login.ZhuceView;
import org.example.controller.UserOne;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class ZhuceHandler extends KeyAdapter implements ActionListener {

    private ZhuceView zhuceView;
    public ZhuceHandler(ZhuceView zhuceView) {
        this.zhuceView = zhuceView;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        JButton jButton= (JButton) e.getSource();
        String text = jButton.getText();
        if ("注册".equals(text)) {
            zhuce();
        }else if ("返回".equals(text)) {
            new LoginView();
            zhuceView.dispose();
        }
    }

    private void zhuce() {
        //注册
        //获取输入的数据
        String username = zhuceView.getUserTxt().getText();
        char[] chars = zhuceView.getPwdField().getPassword();
        String role=zhuceView.getroleTxt().getText();
        String pwd=new String(chars);
        //访问注册接口
        UserOne user = new UserOne();
        if (username.isEmpty() && pwd.isEmpty()) {
            JOptionPane.showMessageDialog(zhuceView, "请输入账号密码后在注册！");
        } else {
            int insert = user.insert(username, pwd,role);
            if (insert > 0) {
                JOptionPane.showMessageDialog(zhuceView, "注册成功");
                zhuceView.dispose();
                new LoginView();
            } else {
                JOptionPane.showMessageDialog(zhuceView, "注册失败");
            }
        }

    }
    @Override
    public void keyPressed(KeyEvent e) {
        if (KeyEvent.VK_ENTER== e.getKeyCode()) {
            zhuce();
        }

    }
}
